package huxibianjie.com.lbscandroid.ui.new_activity;

import android.annotation.SuppressLint;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.Map;

import huxibianjie.com.lbscandroid.Constants;
import huxibianjie.com.lbscandroid.R;
import huxibianjie.com.lbscandroid.base.BaseActivity;
import huxibianjie.com.lbscandroid.event.ClickEvent;
import huxibianjie.com.lbscandroid.manager.RouteManager;
import huxibianjie.com.lbscandroid.manager.UserManager;
import huxibianjie.com.lbscandroid.model.UserModel;
import huxibianjie.com.lbscandroid.task.Callback;
import huxibianjie.com.lbscandroid.task.Task;
import huxibianjie.com.lbscandroid.ui.Service;
import huxibianjie.com.lbscandroid.util.StringUtils;
import huxibianjie.com.lbscandroid.util.SystemUtils;
import huxibianjie.com.lbscandroid.util.Utils;

/**
 * 个人中心
 */
public class MyPageActivity extends BaseActivity implements View.OnClickListener {
    private TextView tvOutLogin, tvMyPhone, tvMyAssets, tvMyEnergy;

    private TextView tvMoneyExtractionBtn, tvPurseAddress, tvPurseAddressBtn;

    private RelativeLayout layPurseDown, layAccountDetails, layWithdraw;

    private UserModel userModel;

    private String paste = "";//黏贴的内容

    @Override
    protected int getContentView() {
        return R.layout.activity_mypage;
    }

    @SuppressLint("WrongViewCast")
    @Override
    protected void initView() {
        initTitle(R.drawable.ic_back, "个人中心");
        tvOutLogin = findViewById(R.id.tv_out_login);

        tvMyPhone = findViewById(R.id.tv_my_phone);
        tvMyAssets = findViewById(R.id.tv_my_assets);
        tvMyEnergy = findViewById(R.id.tv_my_energy);

        tvMoneyExtractionBtn = findViewById(R.id.tv_money_extraction_btn);
        tvPurseAddress = findViewById(R.id.tv_purse_address);
        tvPurseAddressBtn = findViewById(R.id.tv_purse_address_btn);

        layPurseDown = findViewById(R.id.lay_purse_down);

        layAccountDetails = findViewById(R.id.lay_account_details);
        layWithdraw = findViewById(R.id.lay_withdraw);


    }

    @Override
    protected void initData() {
        if (UserManager.getInstance().isLogin()) {
            userModel = UserManager.getInstance().getUserModel();

            tvMyPhone.setText(String.valueOf(Utils.starPhone(userModel.getPhone())));
            tvMyAssets.setText(String.valueOf("我的资产：" + userModel.getMoney() + "枚"));
            tvMyEnergy.setText(String.valueOf("双倍能量：" + userModel.getGoldPool()));

            addressState();
        }
    }

    private void addressState() {
        if (userModel == null) return;
        String purseAddress = userModel.getPurseAddress();
        if (purseAddress.length() < 42) {
            tvPurseAddress.setText("请黏贴钱包地址");
            tvPurseAddress.setEnabled(true);
            tvPurseAddressBtn.setText("确定");
            tvPurseAddressBtn.setSelected(false);
        } else {
            tvPurseAddress.setText("钱包地址已绑定");
            tvPurseAddress.setEnabled(false);
            tvPurseAddressBtn.setSelected(true);
            tvPurseAddressBtn.setText("更换");
        }
    }

    @Override
    protected void initListener() {
        tvOutLogin.setOnClickListener(this);
        tvPurseAddress.setOnClickListener(this);
        tvPurseAddressBtn.setOnClickListener(this);
        tvMoneyExtractionBtn.setOnClickListener(this);
        layPurseDown.setOnClickListener(this);
        layAccountDetails.setOnClickListener(this);
        layWithdraw.setOnClickListener(this);
    }

    @Override
    public void onClickEvent(ClickEvent event) {
        super.onClickEvent(event);
        switch (event.type) {
            case REFRESH_USER_INFO_SUCCESS:
                initData();
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.lay_withdraw:
                RouteManager.getInstance().showWithdrawActivity(this);
                break;
            case R.id.lay_account_details:
                RouteManager.getInstance().showAccountDetailsActivity(this);
                break;
            case R.id.lay_purse_down:
                SystemUtils.openBrowser(this, Constants.Wallet_Url);
                break;
            case R.id.tv_money_extraction_btn:
                if (!(userModel != null && userModel.getPurseAddress().length() == 42)) {
                    showToast("地址错误，请重新绑定");
                    return;
                }
                if (Double.valueOf("5000.0") <= userModel.getMoney()) {
                    showLoading();
                    Task.create(Service.class).savePurseAddress(String.valueOf(userModel.getId()), userModel.getPurseAddress(),
                            String.valueOf(userModel.getMoney())).enqueue(new Callback<Map<String, String>>() {
                        @Override
                        public void onSuccess(@Nullable Map<String, String> mapData) {
                            cancelLoading();
                            Map<String, String> map = new HashMap();
                            map.put("phone", userModel.getPhone());
                            map.put("money", String.valueOf(userModel.getMoney()));
                            MobclickAgent.onEvent(MyPageActivity.this, "Put_forward", map);
                            UserManager.getInstance().save(UserManager.getInstance().getUserModel().setMoney(0),
                                    false);
                            EventBus.getDefault().post(new ClickEvent(ClickEvent.Type.REFRESH_USER_INFO_SUCCESS, null, ""));
                            initData();
                            new android.support.v7.app.AlertDialog.Builder(MyPageActivity.this).setMessage("提现成功")
                                    .setPositiveButton("确定", null).show();
                        }

                        @Override
                        public void onFailure(@NonNull String error) {
                            cancelLoading();
                            new android.support.v7.app.AlertDialog.Builder(MyPageActivity.this).setMessage(error)
                                    .setPositiveButton("确定", null).show();
                        }
                    });
                } else {
                    showToast("提现币数最少为5000LBSC");
                }
                break;
            case R.id.tv_out_login:
                android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(this);
                builder.setTitle("提示");
                builder.setMessage("确定退出登录？");
                builder.setPositiveButton("取消", null);
                builder.setNegativeButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        UserManager.getInstance().logout();
                        finish();
                    }
                });
                builder.show();
                break;
            case R.id.tv_purse_address:
                ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                if (cm != null) {
                    try {
                        paste = (String) cm.getText();
                        if (!StringUtils.isEmpty(paste) && paste.length() == 42) {
                            tvPurseAddress.setText(paste);
                        } else {
                            showToast("请您复制钱包地址后黏贴~");
                        }
                    } catch (Exception e) {
                        showToast("请您复制钱包地址后黏贴~");
                    }
                }
                break;
            case R.id.tv_purse_address_btn:
                if (!tvPurseAddressBtn.isSelected()) {
                    if (paste != null && paste.length() == 42) {
                        showLoading();
                        Task.create(Service.class).updatePurseAddress(String.valueOf(userModel.getId()), paste).enqueue(new Callback<String>() {
                            @Override
                            public void onSuccess(@Nullable String data) {
                                cancelLoading();
                                if (data != null) {
                                    userModel.setPurseAddress(paste);
                                    UserManager.getInstance().save(userModel, false);
                                    addressState();
                                    new android.support.v7.app.AlertDialog.Builder(MyPageActivity.this).setMessage("绑定成功")
                                            .setPositiveButton("确定", null).show();
                                } else {
                                    new android.support.v7.app.AlertDialog.Builder(MyPageActivity.this).setMessage("绑定失败")
                                            .setPositiveButton("确定", null).show();
                                }
                            }

                            @Override
                            public void onFailure(@NonNull String error) {
                                cancelLoading();
                                new android.support.v7.app.AlertDialog.Builder(MyPageActivity.this).setMessage(error)
                                        .setPositiveButton("确定", null).show();
                            }
                        });

                    } else {
                        showToast("您没有黏贴钱包地址或地址错误！");
                    }
                } else {
                    tvPurseAddress.setText("请黏贴钱包地址");
                    tvPurseAddress.setEnabled(true);
                    tvPurseAddressBtn.setText("确定");
                    tvPurseAddressBtn.setSelected(false);
                }
                break;
        }
    }
}
